package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.io.util.StreamUtils;
import org.apache.hbase.thirdparty.io.netty.util.internal.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 登录
     * @param
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {

        Map<String,Object> result = new HashMap<>();
        //如果都不会空 则正常登录
        if(StringUtils.isNotEmpty(loginDto.getPassword()) &&
                StringUtils.isNotEmpty(loginDto.getPhone())){
            //根据手机号查询用户信息
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser apUser = apUserMapper.selectOne(wrapper);
            //如果用户不存在
            if (apUser==null){
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //获取盐
            String salt = apUser.getSalt();
            //将输入的密码+salt md5
            String inputPs = loginDto.getPassword() + salt;
            String inputPsMD5 = DigestUtils.md5DigestAsHex(inputPs.getBytes());
            //与数据库密码对比
            if(!inputPsMD5.equals(apUser.getPassword())){
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //构造返回结果
                //去除敏感数据
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            apUser.setPassword("");
            result.put("user",apUser);
            result.put("token",token);
        }
        //游客登录
        else{
            String token = AppJwtUtil.getToken(0L);
            result.put("token",token);
        }
        return ResponseResult.okResult(result);
    }
}